<template>
  <div>
    <home-page v-show="pageName === 'HomePage'" ref="HomePage"></home-page>
    <cart-page v-if="pageName === 'CartPage'" ref="CartPage"></cart-page>
    <mine-page v-if="pageName === 'MinePage'" ref="MinePage"></mine-page>
    <tabBot ref="tabBot"></tabBot>
    <div v-if="topicMask" class="topicMask">
      <div class="topicMask1">{{ topicMaskMsg }}</div>
    </div>
  </div>
</template>

<script>
import HomePage from './home.vue'
import CartPage from '../cart/cart.vue'
import MinePage from '../ucenter/index/index.vue'

import * as $utils from '../../utils/utils.js'
let app = getApp()

export default {
  components: {
    HomePage,
    CartPage,
    MinePage,
  },
  data() {
    return {
      pageName: '',
      timer: null,
      topicMask: false,
      topicMaskMsg: '',
    }
  },
  onLoad() {
    let tempStr = location.href
      .split('?')
      .slice(-1)[0]
      .split('#')[0]
    let code1 = $utils.StrQuery(tempStr, 'myId')
    let topic1 = uni.getStorageSync('topic')
    setTimeout(() => {
      if (code1) {
        if (topic1) {
          if (code1 != topic1.id) {
            uni.clearStorageSync()
          }
        } else {
          uni.clearStorageSync()
        }
        this.$refs.HomePage.myId = code1
        this.set_onShow()
      } else {
        if (topic1) {
          this.$refs.HomePage.myId = topic1.id
        } else {
          this.$refs.HomePage.myId = '41'
        }
        this.set_onShow()
      }
    }, 100)
  },
  onShow() {
    this.set_onShow()
  },
  mounted() {
    let token = uni.getStorageSync('token')
    if (location.href.includes('redirectLoginPage') && !token) {
      this.wxCodeAuth()
    }
    //this.AuthLoginByJsapi()
    // this.wxShare();
  },
  computed: {
    tabBotName() {
      return this.$store.state.app.tabBotName
    },
  },
  methods: {
    topicMaskDoor(i, j) {
      this.topicMask = i
      this.topicMaskMsg = j || ''
      if (this.topicMask) {
        this.pageName = 'HomePage'
        this.$store.dispatch('app/on_tabBotName', this.$store.state.app.tabsList[0])
      }
    },
    set_onShow() {
      if (this.timer) clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.$refs.HomePage.on_Show()
        if (this.pageName === 'CartPage') {
          this.$refs.CartPage.on_Show()
        }
        if (this.pageName === 'MinePage') {
          this.$refs.MinePage.on_Show()
        }
      }, 20)
      if (this.tabBotName) {
        this.pageName = this.tabBotName.pageName
      }
      this.CartGoodsCount()
    },
    CartGoodsCount() {
      let token = uni.getStorageSync('token')
      if (!token) return
      this.$api('CartGoodsCount')
        .then((res) => {
          this.$store.dispatch('app/on_CartGoodsNum', res.data)
        })
        .catch(() => {})
    },
    // =======
    AuthLoginByJsapi() {
      this.$api(
        'AuthLoginByJsapi',
        {
          url: location.href,
        },
        'POST'
      )
        .then((res) => {
          this.wxShare(res.data)
        })
        .catch((err) => {
          this.topicMaskDoor(true, '授权失败！')
          console.log(err)
        })
    },
    wxShare(res1) {
      let wx = window.wxSDK

      /* wx.config({
        // debug: true,
        appId: res1.appId,
        timestamp: res1.timestamp,
        nonceStr: res1.nonceStr,
        signature: res1.signature,
        jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData', 'chooseWXPay'],
      }) */

      wx.ready(() => {
        let topic = uni.getStorageSync('topic')
        let ids = topic.id || 41
        let title = topic.subtitle || '泽超新福礼'
        let desc = topic.content || '快来参与吧！'
        let img = topic.picUrl || window.location.origin + 'logo.jpg'
        let link = window.location.origin + '?myId=' + ids

        wx.updateAppMessageShareData({
          title: title,
          desc: desc,
          link: link,
          imgUrl: img,
          success: () => {},
        })
        wx.updateTimelineShareData({
          title: title,
          link: link,
          imgUrl: img,
          success: () => {},
        })
      })

      /* wx.error((response) => {
        console.log(response)
      }) */
    },
    wxCodeAuth() {
      const wxLoginConfig = {
        appid: 'wxb53a718a8c5450fe',
        redirect_uri:
          'http://test.zechaoxinxi.com/baseService/public/getIndex/toUrl?type=' +
          location.origin +
          '?redirectLoginPage',
        response_type: 'code',
        scope: 'snsapi_userinfo',
      }

      const onWxCode = () => {
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?${$utils.qsStringify(
          wxLoginConfig
        )}&state=STATE#wechat_redirect`
      }

      const getWxCode = () => {
        return new Promise((resolve, reject) => {
          const code = $utils.urlQuery('code')
          if (!code) {
            let tempStr = location.href
              .split('?')
              .slice(-1)[0]
              .split('#')[0]
            let code1 = $utils.StrQuery(tempStr, 'code')
            if (code1) {
              resolve(code1)
            } else {
              reject()
            }
          } else {
            resolve(code)
          }
        })
      }

      getWxCode()
        .then((res) => {
          this.$api(
            'AuthLoginByH5WX',
            {
              code: res,
            },
            'POST'
          )
            .then((res1) => {
              uni.setStorageSync('userInfo', res1.data.userInfo)
              uni.setStorageSync('token', res1.data.token)
              app.globalData.hasLogin = true
              this.set_onShow()

              this.$refs.HomePage.loginToGoodsId()

              this.topicMask = true
              this.topicMaskMsg = '登录中，请稍等'
            })
            .catch(() => {
              // uni.showModal({
              //   title: '提示',
              //   content: '授权异常!',
              //   showCancel: false,
              //   success: function(res) {
              //     if (res.confirm) {
              //       onWxCode()
              //     } else if (res.cancel) {
              //       console.log('用户点击取消')
              //     }
              //   },
              // })
            })
        })
        .catch(() => {
          onWxCode()
        })
    },
  },
}
</script>

<style scoped>
.topicMask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
}
.topicMask1 {
  background: #fff;
  width: 70vw;
  padding: 40rpx 0;
  border-radius: 14rpx;
  text-align: center;
  font-size: 40rpx;
}
</style>
